package com.baidu.encrypt.controller;

import com.baidu.encrypt.common.utils.SM4Util;
import com.baidu.sggc.audit.extend.AuditExtendContext;
import com.baidu.sggc.audit.extend.GeneralMessage;
import com.baidu.sggc.core.annotation.AuditLog;
import com.baidu.sggc.core.common.R;
import com.baidu.sggc.core.common.utils.MinioUtil;
import com.baidu.encrypt.entity.SampleInfo;
import com.baidu.sggc.entity.UserContext;
import com.baidu.encrypt.service.SampleInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sample")
@Tag(name = "样本信息")
@CrossOrigin(origins = "*")
@Slf4j
public class SampleInfoController {

    @Autowired
    private SampleInfoService sampleInfoService;

    @Autowired
    private SM4Util sm4Util;

    /**
     * 分页查询样本列表
     */
    @GetMapping("/list")
    @Operation(summary = "样本列表", description = "分页查询样本列表，支持按名称筛选")
    @AuditLog(module = "样本管理", auditObject = "样本", operation = "listQuery", message = "查询样本列表")
    public R<Page<SampleInfo>> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name) {

        // 构建审计日志查询条件
        Map<String, String> condition = new LinkedHashMap<>();
        condition.put("样本名称", name);

        Map<String, Object> queryCriteria = new LinkedHashMap<>();
        queryCriteria.put("查询条件", condition);

        Map<String, Object> extendData = new LinkedHashMap<>();
        extendData.put("query_criteria", queryCriteria);
        AuditExtendContext.setExtendData(extendData);

        // 构建查询条件
        QueryWrapper<SampleInfo> wrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            try {
                wrapper.like("name", sm4Util.encrypt(name));
            } catch (Exception e) {
                throw new RuntimeException("加密查询条件失败", e);
            }
        }

        Page<SampleInfo> resultPage = sampleInfoService.page(new Page<>(pageNum, pageSize), wrapper);
        return R.ok(resultPage);
    }

    /**
     * 新增样本（带文件上传）
     */
    @PostMapping("/add")
    @Operation(summary = "新增样本", description = "新增样本信息")
    @AuditLog(module = "样本管理", auditObject = "样本", operation = "create", message = "新增样本")
    public R add(@RequestBody SampleInfo sampleInfo) {

        // 设置创建信息
        sampleInfo.setCreatedTime(new Date());
        String userId = UserContext.getUserId();
        if (userId != null) {
            sampleInfo.setCreatedBy(userId);
        }

        boolean result = sampleInfoService.save(sampleInfo);

        // 构建审计日志信息
        GeneralMessage msg = new GeneralMessage();
        msg.setDataType("样本");
        msg.setDataName(sampleInfo.getName());
        msg.setUniqueIdentification(Collections.singletonList(String.valueOf(sampleInfo.getId())));
        msg.setOperationNum(1);

        AuditExtendContext.setExtendData(toMap(msg));

        return R.ok(result);
    }

    /**
     * 编辑样本（支持文件更新）
     */
    @PostMapping("/update")
    @Operation(summary = "更新样本", description = "更新样本信息")
    @AuditLog(module = "样本管理", auditObject = "样本", operation = "update", message = "更新样本")
    public R update(@RequestBody SampleInfo sampleInfo) {

        // 设置更新时间
        sampleInfo.setUpdatedTime(new Date());

        boolean result = sampleInfoService.updateById(sampleInfo);

        // 构建审计日志信息
        GeneralMessage msg = new GeneralMessage();
        msg.setDataType("样本");
        msg.setDataName(sampleInfo.getName());
        msg.setUniqueIdentification(Collections.singletonList(String.valueOf(sampleInfo.getId())));
        msg.setOperationNum(1);

        AuditExtendContext.setExtendData(toMap(msg));

        return R.ok(result);
    }

    /**
     * 查询样本详情
     */
    @GetMapping("/detail/{id}")
    @Operation(summary = "样本详情", description = "通过ID查询样本详细信息")
    @AuditLog(module = "样本管理", auditObject = "样本", operation = "detailsQuery", message = "查询样本详情")
    public R<SampleInfo> detail(@PathVariable Long id) {
        // 构建审计日志上下文
        Map<String, Object> extendData = new LinkedHashMap<>();
        Map<String, Object> queryCriteria = new LinkedHashMap<>();
        Map<String, Object> condition = new LinkedHashMap<>();
        condition.put("唯一标识", id);
        queryCriteria.put("查询条件", condition);
        extendData.put("query_criteria", queryCriteria);
        AuditExtendContext.setExtendData(extendData);

        SampleInfo sampleInfo = sampleInfoService.getById(id);
        return R.ok(sampleInfo);
    }

    /**
     * 批量删除样本
     */
    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除样本", description = "通过ID列表批量删除样本")
    @AuditLog(module = "样本管理", auditObject = "样本", operation = "delete", message = "批量删除样本")
    public R batchDelete(@RequestBody List<Long> ids) {
        // 构建审计日志信息（Java 8适配）
        GeneralMessage msg = new GeneralMessage();
        msg.setDataType("样本");
        msg.setUniqueIdentification(ids.stream()
                .map(String::valueOf)
                .collect(Collectors.toList()));
        msg.setOperationNum(ids.size());
        AuditExtendContext.setExtendData(toMap(msg));

        boolean result = sampleInfoService.removeByIds(ids);
        return R.ok(result);
    }

    /**
     * 对象转Map工具方法（适配Java 8）
     */
    private Map<String, Object> toMap(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.convertValue(obj, Map.class);
    }
}